package com.expert.conrtoller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.expert.annotations.RoleAnnotation;
import com.expert.constant.JwtClaimConstant;
import com.expert.constant.RedisKeyConstant;
import com.expert.dto.UpdatePasswordDTO;
import com.expert.dto.UserDTO;
import com.expert.dto.UserLoginDTO;
import com.expert.enums.RoleLevel;
import com.expert.pojo.User;
import com.expert.properties.JwtProperties;
import com.expert.result.Result;
import com.expert.service.UserService;
import com.expert.util.JwtUtil;
import com.expert.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: UserController
 * @Author: cxs
 * @Date: 2024/01/18 19:53
 * @Description:
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/login")
    public Result<UserLoginVo> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);
        User user = userService.login(userLoginDTO);
        //生成令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimConstant.USER_ID, user.getId());
        String accessToken = JwtUtil.createJWT(jwtProperties.getAccessSecretKey(), jwtProperties.getAccessTtl(), claims);
        String refreshToken = JwtUtil.createJWT(jwtProperties.getRefreshSecretKey(), jwtProperties.getRefreshTtl(), claims);
        //将refreshToken存入redis
        redisTemplate.opsForValue().set(
                RedisKeyConstant.REFRESH_TOKEN + user.getAccount(),
                refreshToken, jwtProperties.getRefreshTtl(), TimeUnit.MILLISECONDS
        );
        UserLoginVo userLoginVo = UserLoginVo.builder()
                .id(user.getId())
                .name(user.getName())
                .account(user.getAccount())
                .accessToken(accessToken)
                .refreshToken(refreshToken)
                .build();
        return Result.success(userLoginVo);
    }

    /**
     * 生成验证码
     *
     * @return
     */
    @GetMapping("/captchaImage")
    public Result<CheckCodeVo> createCheckCode() {
        log.info("生成验证码");
        CheckCodeVo checkCodeVo = userService.createCode();
        return Result.success(checkCodeVo);
    }

    /**
     * 获取用户信息
     * @param account
     * @return
     */
    @RoleAnnotation(level = RoleLevel.ALL)
    @GetMapping("/info/{account}")
    public Result<User> getUserInfo(@PathVariable("account") String account){
        log.info("获取用户信息");
        return Result.success(userService.getUserInfo(account));
    }
    /**
     * 获取用户信息
     * @param id
     * @return
     */
    @RoleAnnotation(level = RoleLevel.ALL)
    @GetMapping("/getById/{id}")
    public Result<User> getUserById(@PathVariable("id") Long id){
        log.info("获取用户信息");
        return Result.success(userService.getUserById(id));
    }
    /**
     * 分页查询用户信息
     * @param page 当前页码
     * @param pageSize  每页条数
     * @param account 查询账号
     * @param name  用户名字
     * @return  分页的信息
     */
    @RoleAnnotation(level = RoleLevel.ADMIN)
    @GetMapping("/page")
    public Result<Page<UserPageVo>> userPage(int page,int pageSize,String account,String name){
        log.info("分页查询用户：{}，{}，{}，{}",page,pageSize,account,name);
        Page<UserPageVo> userPageResult=userService.pageUsers(page,pageSize,account,name);
        return Result.success(userPageResult);
    }
    @RoleAnnotation(level = RoleLevel.ADMIN)
    @PutMapping("/updateStatus/{id}/{status}")
    public Result update(@PathVariable("id") Long id, @PathVariable("status")Integer status){
        log.info("修改用户信息：{},{}",id,status);
        userService.updateUserStatus(id,status);
        return  Result.success();
    }

    /**
     * 删除用户信息
     * @param ids
     * @return
     */
    @RoleAnnotation(level = RoleLevel.ADMIN)
    @DeleteMapping("/delete")
    public Result delete(@RequestParam List<Long> ids){
        log.info("删除用户信息：{}",ids);
        userService.deleteUsers(ids);
        return  Result.success();
    }

    @RoleAnnotation(level = RoleLevel.ALL)
    @PutMapping("/update")
    public Result update(@RequestBody UserDTO userDTO){
        log.info("修改用户信息:{}",userDTO);
        userService.updateUserById(userDTO);
        return  Result.success();
    }
    @RoleAnnotation(level = RoleLevel.ADMIN)
    @PutMapping("/{id}")
    public Result update(@PathVariable("id") Long id){
        log.info("修改用户信息:{}",id);

        userService.resetPassword(id);
        return  Result.success();
    }
    @RoleAnnotation(level = RoleLevel.ADMIN)
    @PostMapping("/add")
    public Result add(@RequestBody UserDTO userDTO){
        log.info("添加用户信息:{}",userDTO);
        userService.addUser(userDTO);
        return  Result.success();
    }

    @RoleAnnotation(level = RoleLevel.ADMIN)
    @GetMapping("/selectByName")
    public Result<List<RemoteUserVo>> selectByName(@RequestParam String name){
        log.info("根据名字查询用户");
       List<RemoteUserVo> list= userService.selectByName(name);
        return  Result.success(list);
    }

    /**
     * 修改密码
     * @param passwordDTO
     * @return
     */
    @PostMapping("/updateUserPassword")
    public Result updateUserPassword(@RequestBody UpdatePasswordDTO passwordDTO){
        this.userService.updateUserPassword(passwordDTO);
        return Result.success();
    }
    @GetMapping("/getUserHomeInfo")
    public Result<UserHomeInfoVo> getUserHomeInfo(){
        UserHomeInfoVo userHomeInfoVo=this.userService.getUserHomeInfo();
        return Result.success(userHomeInfoVo);
    }
}
